<template>
    <div class="container">
        <div class="form">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                <el-form-item label="角色名称:">
                    <el-input v-model="formInline.name" placeholder="请输入角色名称" clearable />
                </el-form-item>
                <el-form-item label="描述信息:">
                    <el-input v-model="formInline.desc" placeholder="请输入信息描述" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd" v-permission="'sys:role:create'">添加</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div>
            <el-table :data="tableData" style="width: 100%" border>
                <el-table-column label="角色名称" prop="name" />
                <el-table-column label="描述" prop="desc" />
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button size="small" type="primary" @click="handleEdit(scope.row)" v-permission="'sys:role:update'">修改</el-button>
                        <el-button size="small" type="primary" @click="handlePower(scope.row)">授权</el-button>
                        <el-button size="small" type="danger" @click="handleDelete(scope.row)" v-permission="'sys:role:delete'">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div>
            <Pagetion v-bind="pagetio" @page-change="pageChange"></Pagetion>
        </div>
        <div>
            <el-backtop target=".el-main" :right="100" :bottom="100" ref="backTop" :visibility-height="20" />
        </div>
        <div>
            <el-dialog v-model="dialogTableVisible" :title="title">
                <div v-if="title == '修改信息'">
                    <el-form :inline="true" :model="editForm" class="demo-form-inline">
                        <el-form-item label="角色名称:">
                            <el-input v-model="editForm.name" placeholder="请输入角色名称" clearable />
                        </el-form-item>
                        <el-form-item label="描述信息:">
                            <el-input v-model="editForm.desc" placeholder="请输入信息描述" clearable />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="confirmEdit">修改</el-button>
                        </el-form-item>
                    </el-form>
                </div>
                <div v-else>
                    <el-tree :data="dataSource" show-checkbox node-key="id" ref="treeRef" :default-expand-all="false"
                        :expand-on-click-node="false" :default-checked-keys="checkedArr">
                        <template #default="{ node, data }">
                            <span>{{ node.label }}</span>
                            <span class="tree">{{ data.id }}</span>
                        </template>
                    </el-tree>
                </div>
                <template #footer  v-if="title != '修改信息'">
                    <span class="dialog-footer">
                        <el-button @click="dialogTableVisible = false">取消</el-button>
                        <el-button type="primary" @click="confirmPower">确认</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick } from 'vue'
import { post } from "@/http/request";
import { ClassPagination } from "#/index";
import { ElMessage, ElMessageBox } from 'element-plus';
import Pagetion from "@/components/pagetion/Pagetion.vue";

const pagetio = reactive(new ClassPagination())
const backTop = ref()//回到顶部组件ref
const tableData = ref<TypeRole[]>([])//接收表格数据
const dialogTableVisible = ref(false)//弹窗是否显示
const title = ref('')//弹窗title
const dataSource = ref<Tree[]>([])//权限列表数据
const checkedArr = ref([])//已选中
const rowId = ref(0)//配置权限需要传递的roleId
const treeRef = ref()


// 初始化数据传递的参数
let params = reactive({
    _gp: "admin.role",
    _mt: "list",
    page: pagetio.pageNo,
    limit: pagetio.pageSize
})

// 修改弹窗表单
const editForm = reactive({
    id: 0,
    name: "",
    desc: ""
})

// 添加表单
const formInline = reactive({
    name: '',
    desc: '',
})
const formAdd = reactive({...formInline})

// 初始化数据
const loadInit = () => {
    post(params).then(res => {
        console.log(res);
        let { errmsg, errno, data } = res
        if (200 == errno) {
            tableData.value = data.items
            pagetio.total = data.total
        } else {
            tableData.value = []
            ElMessage.error(errmsg)
        }
    })
}
loadInit()

// 添加
const handleAdd = () => {
    if (formInline.name == '') {
        return ElMessage.warning('角色名称不能为空')
    }
    let addParams = reactive({
        _gp: "admin.role",
        _mt: "create",
        role: JSON.stringify({ ...formInline })
    })
    post(addParams).then(res => {
        // console.log(res);
        let { errno, errmsg } = res
        if (200 == errno) {
            ElMessage.success("添加成功")
            loadInit()
            Object.assign(formInline,formAdd)
        } else {
            ElMessage.error(errmsg)
        }
    })
}

// 修改
const handleEdit = (row: TypeRole) => {
    title.value = "修改信息"
    editForm.id = row.id
    editForm.name = row.name
    editForm.desc = row.desc
    dialogTableVisible.value = true
}

// 确认修改
const confirmEdit = () => {
    if (editForm.name == '') {
        return ElMessage.warning('角色名称不能为空')
    }
    let editParams = reactive({
        _gp: "admin.role",
        _mt: "update",
        role: JSON.stringify({ ...editForm })
    })
    post(editParams).then(res => {
        console.log(res);
        let { errmsg, errno } = res
        if (200 == errno) {
            ElMessage.success("修改成功")
            dialogTableVisible.value = false
            loadInit()
        } else {
            ElMessage.error(errmsg)
        }
    })
}

// 授权
const handlePower = (row: TypeRole) => {
    title.value = "权限配置"
    rowId.value = row.id
    let data = {
        _gp: "admin.role",
        _mt: "permissionList",
        roleId: row.id
    }
    checkedArr.value = []
    post(data).then(res => {
        console.log(res);
        let { errmsg, errno, data } = res
        if (200 == errno) {
            dataSource.value = data.systemPermissions
            checkedArr.value = data.assignedPermissions
            nextTick(() => {
                dialogTableVisible.value = true
            })
        } else {
            ElMessage.error(errmsg)
        }
    })
}

// 权限配置确认按钮
const confirmPower = ()=>{
    let data = {
        _gp: "admin.role",
        _mt: "permissionSet",
        roleSetPermissionDTO:JSON.stringify({
            roleId:rowId.value,
            permissions:treeRef.value.getCheckedKeys(true)
        })
    }
    post(data).then(res=>{
        console.log(res);
        let {errno,errmsg}  = res
        if(200==errno){
            ElMessage.success("设置成功")
            dialogTableVisible.value = false
        }else{
            ElMessage.error(errmsg)
        }
    })
}

// 删除
const handleDelete = (row: TypeRole) => {
    ElMessageBox.confirm(
        '是否删除此角色?',
        "提示",
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        let delParams = reactive({
            _gp: "admin.role",
            _mt: "delete",
            roleId: row.id
        })
        post(delParams).then(res => {
            console.log(res);
            let { errmsg, errno } = res
            if (200 == errno) {
                ElMessage.success("删除成功")
                loadInit()
            } else {
                ElMessage.error(errmsg)
            }
        })
    })
}

// 分页组件子传父自定义事件
const pageChange = (e: TypePage) => {
    params.page = e._pageNo
    params.limit = e._pageSize
    loadInit()
    nextTick(() => {
        backTop.value.$el.click?.()
    })
}
</script>

<style lang="less" scoped>
.el-input {
    width: 200px;
}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}

.tree {
    position: absolute;
    right: 0;
}
</style>